<?php
/*
 * @author eBIZ Team <dev@jungo.com.cn>
 * @copyright  Copyright (c) , ShenZhen JunGO Technology Co., Ltd. All rights reserved.
 * @license  Commercial authorization, unauthorized use and modification are prohibited
 * @url www.jungo.com.cn
 */

namespace ckeeper\utils;


class FormUtil
{
    /**
     * 选项数据处理成树形
     * @param array $array 待处理数组数据
     * @param $optionsCallback // 回调函数
     * @param string $pidName 上级字段
     * @param string $childKeyName 子集索引
     * @param int $baseId
     * @return array
     */
    public static function optionsArrayToTree(array $array, $optionsCallback,
                                              string $pidName = 'pid',
                                              string $childKeyName = 'children', int $baseId = 0)
    {
        $options = [];
        foreach ($array as $key => $item) {
            if ($item[$pidName] == $baseId || $baseId === null) {
                unset($array[$key]);
                $topOptions = $optionsCallback($item);
                self::hierarchicalDivision($array, $optionsCallback, $item['id'], $topOptions, $pidName, $childKeyName);
                $options[] = $topOptions;
            }
        }
        return $options;
    }

    /**
     * @param array $optionsList 待处理数据数组
     * @param $optionsCallback // 回调函数
     * @param int $pid 上级id
     * @param $parentOptions // 父级选项
     * @param string $pidName 父级字段名
     * @param string $childKeyName 子集索引
     */
    public static function hierarchicalDivision(array &$optionsList, $optionsCallback,
                                                int $pid, &$parentOptions, string $pidName,
                                                string $childKeyName)
    {
        $childMenuList = [];
        foreach ($optionsList as $key => $item) {
            if ($item[$pidName] == $pid) {
                unset($optionsList[$key]);
                $childMenu = $optionsCallback($item);
                self::hierarchicalDivision($optionsList, $optionsCallback, $item['id'], $childMenu, $pidName, $childKeyName);
                $childMenuList[] = $childMenu;
            }
        }
        if (!empty($childMenuList)) {
            $parentOptions[$childKeyName] = $childMenuList;
        }
    }

}
